package com.fengye.middleware.rabbitmq.boot.demo.basic;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 *
 * @author sky
 * @date 2021年06月09日 11:16 上午
 */
@Component
@Slf4j
public class BasicPublisher {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.basic.info.exchange.name:basic_change_name}")
    private String basicExchangeName;

    @Value("${mq.basic.info.routing.key.name:basic_routing_key_name}")
    private String basicRoutingKeyName;


    // TODO: 接受乱码的问题
    public void sendMsg(String message) {
        if (StringUtils.hasText(message)){
            try {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(basicExchangeName);
                rabbitTemplate.setRoutingKey(basicRoutingKeyName);

                Message msg = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8)).build();
                rabbitTemplate.convertAndSend(msg);

                log.info("基本消息模型：生产者-发送消息：{}", message);
            }catch (Exception e){
                log.error("基本消息模型：生产者-发送消息异常：{}", message, e.fillInStackTrace());
            }
        }
    }
}
